﻿using UnityEngine;
using System.Collections;
using XLua;

[LuaCallCSharp]
public class XluaManager : MonoBehaviour {

    public static XluaManager Instance;

    public LuaEnv luaenv;
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        luaenv = new LuaEnv();
    }


    void Update()
    {
        if (luaenv != null)
        {
            luaenv.Tick();
        }
    }

    void OnDestroy()
    {
        luaenv.Dispose();
    }

    public void InitLuaFile(string filePath, string LuaName)
    {
        string luafile = LuaName + ".lua";//"Main.lua";

        //luafile.Substring(0,luafile.IndexOf('.'));

        string luaFilePath = filePath + luafile;
        Debug.Log("luaFilePath:" + luaFilePath);

        byte[] bytes = FileHelper.Instance.LoadFileBytes(filePath, luafile);

        if (bytes != null)
        {

            XluaManager.Instance.luaenv.AddLoader((ref string filename) =>
            {
                if (filename == LuaName)
                {
                    filename = luaFilePath;
                    return bytes;
                }

                return null;
            });
        }

        string luaScript = @"require '" + LuaName + "'";

        XluaManager.Instance.luaenv.DoString(luaScript);
    }

	
}
